#include "service.h"
#include "math.h"
#include "settings.h"

#include <QFile>
#include <QTextStream>
#include <QSqlQuery>
#include <QSqlError>
#include <QProcess>

#include <QDebug>

Service::Service()
{
}


double Service::round( double value, int digits )
{
    if (value < 0.0)
        return ceil( value * pow(10, digits) + pow(0.1, digits + 1) ) / pow(10, digits);
    else
      return floor( value * pow(10, digits) + pow(0.1, digits + 1) ) / pow(10, digits);
}


#define PAPERSIZE 20

QByteArray Service::centerChequeText(const QString &text){
    int value        = (PAPERSIZE -text.length() > 0)?int((PAPERSIZE -text.length())/2):0;

    return   (QString(value, ' ') + text).toUtf8();
}

QByteArray Service::rightChequeText(const QString &text, int already){
    int value        = (PAPERSIZE -already-text.length() > 0)?int((PAPERSIZE -text.length()-already)):0;

    return   (QString(value, ' ') + text).toUtf8();
}


QByteArray Service::columnsChequeText(const QString &text_left, const QString &text_right){
    int value        = (PAPERSIZE -text_right.length()-text_left.length() > 0)?int((PAPERSIZE -text_right.length()-text_left.length())):0;

    return   (text_left + QString(value, ' ') + text_right).toUtf8();
}


QByteArray Service::leftChequeText(const QString &text){
    return   text.toUtf8();
}

void Service::printCheque(int chequeID)
{
    QSettings *settings = Settings::getInstance();

    QString tmpfile = "/tmp/jPOS_print";

    QFile file(tmpfile);
    if (!file.open(QIODevice::WriteOnly))
        return;


    QTextStream out(&file); //

    out << centerChequeText(Settings::getEssential("РЕКВИЗИТЫ_ЧЕКА0"))<<endl;
    out << centerChequeText(Settings::getEssential("РЕКВИЗИТЫ_ЧЕКА1"))<<endl;
    out << centerChequeText(Settings::getEssential("РЕКВИЗИТЫ_ЧЕКА2"))<<endl;
    out << centerChequeText(Settings::getEssential("РЕКВИЗИТЫ_ЧЕКА3"))<<endl;

    QSqlQuery qDoc;
    qDoc.prepare(settings->value("queries/print/get_document").toString());
    qDoc.bindValue(":document_id", chequeID);

    if(!qDoc.exec()){
        qDebug()<<posInFile<<qDoc.lastError().text()<<endl<<qDoc.lastQuery()<<endl<<qDoc.boundValues();
        return;
    }
    qDoc.next();

    out << endl;
    out << centerChequeText("Чек №"+qDoc.value(6).toString())<< endl;
    out << leftChequeText(qDoc.value(0).toString()+" "+qDoc.value(1).toString().left(8))<< endl;
    out << endl;
    out << leftChequeText(QString(PAPERSIZE,'-'))<<endl;
    QSqlQuery qGoods;
    qGoods.prepare(settings->value("queries/print/get_document_pos").toString());
    qGoods.bindValue(":document_id", chequeID);

    if(!qGoods.exec()){
        qDebug()<<posInFile<<qGoods.lastError().text()<<endl<<qGoods.lastQuery()<<endl<<qGoods.boundValues();
        return;
    }

    while (qGoods.next()){
        out << leftChequeText(qGoods.value(0).toString()) << endl;
        out << columnsChequeText(QString::number(qGoods.value(1).toDouble(),'f', 3)+"*"+QString::number(qGoods.value(2).toDouble(),'f', 2), QString::number(qGoods.value(3).toDouble(),'f', 2))<<endl;
        out << endl;
    }

    out << leftChequeText(QString(PAPERSIZE,'-'))<<endl;

    double summ = qDoc.value(4).toDouble();
    out << columnsChequeText("Сумма", QString::number(qDoc.value(4).toDouble(),'f', 2))<<endl;

    out << leftChequeText(QString(PAPERSIZE,'-'))<<endl;

    double pay = qDoc.value(5).toDouble();
    if (pay>0){
        out << columnsChequeText("Оплата", QString::number(pay,'f', 2))<<endl;
        double retn = pay - summ;
        if (retn > 0)
            out << columnsChequeText("Сдача:", QString::number(retn,'f', 2))<<endl;

        out << leftChequeText(QString(PAPERSIZE,'-'))<<endl;
    }


    out <<endl<< centerChequeText("Спасибо за покупку")<<endl;

    out <<endl<< centerChequeText("Нефискальный чек");

    file.close();

    QString dev = settings->value("devices/printer/name").toString();
    if (dev=="none" || dev.isEmpty())
        dev = "";
    else
        dev = " -P "+dev;


   qDebug()<<posInFile<<"lpr "+dev+" "+tmpfile;

    if (!QProcess::startDetached("lpr "+dev+" "+tmpfile))
        qDebug()<<posInFile<<"Error in print"<<endl<<"lpr "+dev+" "+tmpfile;

}
